
// 引入 核心模块 http  http模块不需要下载，随node已经安装到系统中
const http = require('http')
const fs = require('fs')
const server = http.createServer()

const users = [
  {
    id: 1,
    username: "zhangsan"
  },
  {
    id: 1,
    username: "lisi"
  },
  {
    id: 1,
    username: "wangwu"
  }
]

const routesMap = new Map()

routesMap.set("/home", async (req, res) => {
  res.setHeader("content-type", "text/html;charset=utf-8")
  res.write("首页")
})
routesMap.set("/list", async (req, res) => {
  res.setHeader("content-type", "text/html;charset=utf-8")
  res.write("列表")
})

// 监听事件  监听请求 
server.on("request", async (req, res) => {

  let url = req.url
  // 静态路径
  // string 的方法 startsWith 以..开始的字符串
  if (url.startsWith("/public")) {
    content = fs.readFileSync(`.${url}`)
  }
  // 路由表
  let routeHandle = routesMap.get(url)
  await routeHandle(req, res)
  res.end(content)
})
// 监听端口
server.listen(8080)
console.log("running on 8080")
